import React, { Component, useState, useEffect, useRef } from 'react';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import { DownOutlined, PlusOutlined } from '@ant-design/icons';
import CreateForm from './components/CreateForm';
import PersonInfo from './components/personInfo';
import { Button, Table, Divider, Dropdown, Menu, message, Form, Input, Select, Switch, Modal, Alert, Descriptions, Upload } from 'antd';
import { UploadOutlined } from '@ant-design/icons';
import { addRule,cancelClassJoin } from './service';
import { connect } from 'umi';
import { exportResultExcel } from '../basic-form/service';
import axios from 'axios'
import { value } from 'numeral';

const { Option } = Select
const { Search } = Input;

/**
 * 添加节点
 * @param fields
 */

const handleAdd = async fields => {
    const hide = message.loading('正在添加');
    console.log(1111)
    try {
        var a = await addRule({
            desc: fields.desc,
        });
        console.log(a)
        hide();
        message.success('添加成功');
        return true;
    } catch (error) {
        hide();
        message.error('添加失败请重试！');
        return false;
    }
};



const Stepform = (props) => {
    const {
        loading,
        dispatch,
        formAndstepForm: { list },
    } = props;
    const [resetpassvisible, setpassvisible] = useState(false);//重置密码弹框
    const [gradeVisible, setgradeVisible] = useState(false);//成绩查询弹框
    const [personVisible, setpersonVisible] = useState(false);//个人信息弹框
    const [updateModalVisible, handleUpdateModalVisible] = useState(false);
    const [stepFormValues, setStepFormValues] = useState({});
    const [selectedRowKeys, setSelectedRowKeys] = useState([]);//选择列表
    const [data, setdata] = useState([]);//列表数据
    const [detail, setdetail] = useState({});//修改个人数据
    const [currentclass, setcurrentclass] = useState(null);
    let query = useRef({
        pageIndex: 1,
        pageSize: 20,
        name: "",
    })
    useEffect(() => {
        dispatch({
            type: 'formAndstepForm/fetch',
            payload: {
                ...query.current
            },
        });
    }, []);
    const paginationProps = {
        showSizeChanger: true,
        showQuickJumper: true,
        pageSize: query.current.pageSize,
        total: list.total,
        onChange: (pageIndex, pageSize) => {
            query.current = { ...query.current, pageIndex, pageSize }
            console.log(query.current)

            dispatch({
                type: 'formAndstepForm/fetch',
                payload: {
                    ...query.current
                },
            });
            //   console.log(page,currents,pageSize,pagination)            
        },

        onShowSizeChange: (pageIndex, pageSize) => {
            query.current = { ...query.current, pageIndex, pageSize }
            dispatch({
                type: 'formAndstepForm/fetch',
                payload: {
                    ...query.current
                },
            });
        }
    };

    const [form] = Form.useForm();
    const onFinish = async (values) => {
        const fieldsValue = await form.validateFields();
        console.log(fieldsValue)
        query.current = { ...query.current, ...fieldsValue }
        dispatch({
            type: 'formAndstepForm/fetch',
            payload: {
                ...query.current
            },
        });
    };
    const columns = [
        {
            title: '班级代码',
            dataIndex: 'class_code',

        },

        {
            title: '年纪',
            dataIndex: 'grade',
        },
        {
            title: '班级',
            dataIndex: 'class_name',
        },
        {
            title: '老师',
            dataIndex: 'teacher_name',
        },
        {
            title: '操作',
            dataIndex: 'option',
            valueType: 'option',
            render: (_, record) => (
                <>
                    <a onClick={() => { setgradeVisible(true); setcurrentclass(record) }}>成员查看</a>
                    <Divider type="vertical" />
                    {/* 和新建界面一样，用同一个组件，这不过这个根据ID打开那边要获取值 */}


                    <Divider type="vertical" />
                    <a href="#" onClick={()=>{cancelClass(record)}}>取消关联</a>

                </>
            ),
        },
    ];

 // 取消关联
const cancelClass =async (record)=>{
    Modal.confirm({
        title: '取消关联',
        content: '您将不再管理'+record.grade+"—"+record.class_name+' 。\n确定要取消关联吗',
        okText: '确认',
        cancelText: '取消',
        onOk:async () => {
            let res = await cancelClassJoin({classId:record.id})
            if (res) {
                dispatch({
                    type: 'formAndstepForm/fetch',
                    payload: {
                        ...query.current
                    },
                });
            }
        },
      });
}
    //  导出
    const exportExcel = () => {
        let config = {
            headers: {
                'Authorization': `${sessionStorage.getItem('tokenHead')} ${sessionStorage.getItem('token')}`,
            },
            responseType:'blob'
        }
        if (selectedRowKeys.length==0) {
            message.error('当前没有选中数据')
            return

        }
        console.log(selectedRowKeys)
        selectedRowKeys.map(id=>{
            axios.get(`/class/exportResultExcel?classId=${id}`, config)
            .then(res => {
                console.log(res)
                if (res) {
                    let blob = new Blob([res.data], {type: res.data.type}      
                    )
                      var link = document.createElement('a');
                        link.href = window.URL.createObjectURL(blob);
                        var itemname= list.list.find(item=>{
                            return  item.id==id
                         })
                        link.download = itemname.grade+'届'+itemname.class_name+'考试表';              
                        link.click();
                  }else{
                    message.error(res.message)
                  }
            })
            .catch(error => {
                message.error(`file upload failed.`);
            });
        })
       

    }
 

    // 提示
    const onClose = (e) => {
        console.log(e, 'I was closed.');
    };

    //筛选数据
    const onSelectChange = selectedRowKeys => {
        console.log('selectedRowKeys changed: ', selectedRowKeys);
        setSelectedRowKeys(selectedRowKeys);
    };
    const rowSelection = {
        selectedRowKeys,
        onChange: onSelectChange,
    };


    const layout = {
        labelCol: {
            span: 10,
        },
        wrapperCol: {
            span: 10,
        },
    };
    const formRef = React.createRef();
    return (
        <PageHeaderWrapper>
            <div >

                {/* <Modal
                    title="个人信息"
                    visible={personVisible}
                    onOk={() => hidepersonModal(false)}
                    onCancel={() => hidepersonModal(false)}
                    okText="确认"
                    cancelText="取消"
                >
                    <Descriptions title="若信息有误请联系管理员" size='small'>
                        <Descriptions.Item label="账号">Cloud Database</Descriptions.Item>
                        <Descriptions.Item label="姓名" span={2}>Prepaid</Descriptions.Item>
                        <Descriptions.Item label="类型" >18:00:00</Descriptions.Item>
                        <Descriptions.Item label="工号">$80.00</Descriptions.Item>

                    </Descriptions>
                </Modal> */}

                <PersonInfo
                    currentclass={currentclass}
                    onCancel={() => setgradeVisible(false)}
                    modalVisible={gradeVisible}
                />
                <Form layout='inline'>



                    <Form.Item label="">

                        <Button type="primary" onClick={() => { exportExcel() }}>
                            <UploadOutlined /> 导出
                           </Button>
                    </Form.Item>
                </Form>
            </div>
            <div style={{ marginTop: "50px", marginBottom: "20px" }}>
                <Form {...layout} layout='inline' form={form} name="control-ref" >

                    <Form.Item
                        style={{ width: '200px' }}
                        name="name"
                        label="关键字"

                    >

                        <Search
                            placeholder="班级代码，班级年级，班级名称"
                            onSearch={onFinish}
                            style={{ width: 300 }}
                        />
                    </Form.Item>
                </Form>
            </div>
            <Alert
                message='如需变更班级信息，请联系管理员'
                type="warning"
                closable
                onClose={onClose}
            />
            <Table rowSelection={rowSelection} columns={columns} pagination={paginationProps} dataSource={list.list} rowKey={record => record.id} />
        </PageHeaderWrapper>
    )

}
export default connect(({ formAndstepForm, loading }) => ({
    formAndstepForm,
    loading: loading.models.formAndstepForm,
}))(Stepform);